package com.listeningframework.boot.autoconfigure.webmvc.validate;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.listeningframework.boot.commons.string.StringUtils;
import com.listeningframework.boot.commons.string.RegExpUtils;

/**
 * ListeningDecimalPattern Validator
 * @author lixining
 * @version $Id: ListeningDecimalPatternValidator.java, v 0.1 2016年5月5日 下午4:19:01 lixining Exp $
 */
public class ListeningDecimalPatternValidator implements ConstraintValidator<ListeningDecimalPattern, String> {
    /**
     * Error Message
     */
    private String  message;
    /**
     * 小数部分长度
     */
    private Integer scale;
    /**
     * 整数部分长度
     */
    private Integer presion;
    /**
     * 是否允许空
     */
    private boolean allowBlank;

    /**
     * @see javax.validation.ConstraintValidator#initialize(java.lang.annotation.Annotation)
     */
    @Override
    public void initialize(ListeningDecimalPattern constraintAnnotation) {
        this.presion = constraintAnnotation.presion();
        this.scale = constraintAnnotation.scale();
        this.allowBlank = constraintAnnotation.allowBlank();
        this.message = constraintAnnotation.message();
    }

    /**
     * @see javax.validation.ConstraintValidator#isValid(java.lang.Object, javax.validation.ConstraintValidatorContext)
     */
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (allowBlank && StringUtils.isBlank(value)) {
            return true;
        }
        if (RegExpUtils.isDecimal(value, presion, scale)) {
            return true;
        }
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
        return false;
    }

}
